interface IConfig<T> {
  pageSize?: number;
  onFetch: (page: number, pageSize?: number) => Promise<any>;
  onChange: (value: { data: Array<T> }) => void;
}

class ListStore<T> {
  constructor(config: IConfig<T>) {
    const { pageSize } = config;
    if (pageSize) this.pageSize = pageSize;
    this.config = config;
  }

  config: IConfig<T>;

  refreshing = false;
  loading = false;
  nodata = false;
  currentPage = 0;
  pageSize = 20;
  data: Array<T> = [];
  refresh = (reset?: boolean, cb?: () => void) => {
    console.log('[refresh] ', );
    if (this.refreshing) return;
    this.refreshing = true;
    this.currentPage = 0;
    this.loading = false;
    this.nodata = false;
    this.data = [];
    if (!reset) this.loadNext(cb);
  }
  setData = (exec: (data: T[]) => T[]) => {
    this.data = exec(this.data);
    this.config.onChange && this.config.onChange({ data: this.data });
  }
  loadNext = async (cb?: () => void) => {
    console.log('[loadNext] ', )
    if (this.nodata || this.loading) return;
    let pageSize = this.pageSize || 20;
    let currentPage = (this.currentPage += 1);
    try {
      this.loading = true;
      let list = await this.config.onFetch(currentPage, pageSize);
      this.loading = false;
      if (list.length < pageSize) this.nodata = true;
      let listData = this.data.concat(list);
      this.data = listData;
      this.refreshing = false;
      this.config.onChange && this.config.onChange({ data: listData });
      cb && cb();
    } catch (e) {
      console.log('[loadNext e] ', e);
      // 此处增加请求失败后逻辑
      this.loading = false;
      this.refreshing = false;
      cb && cb();
    }
  }
}

export default ListStore;
